import React, { PureComponent, Fragment } from 'react';
import router from 'umi/router';
import { connect } from 'dva';

import {
  Dropdown,
  Button,
  Row,
  Col,
  Tooltip,
  Alert,
  Form,
} from 'antd';
import * as Utils from '@/utils/utils';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import LockBillForm from '@/components/LockInvForm';
import MBLEditForm from './Components/MBLEditForm';
// import Authorized from '@/components/Authorized';

import RenderAuthorized from '@/components/Authorized';

import styles from './Framework.less';

const { Description } = DescriptionList;
const { Group: ButtonGroup } = Button;

const ModelName = 'mbl';

@connect(({ loading, user, mbl }) => ({
  loading: loading.models[ModelName],
  mbl: mbl.current,
  cUser: user.currentUser,
}))
@Form.create()
class Framework extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      lockFormVisible: false,
      current: {}
    }
  }

  tabList = [
    {
      key: 'HBL',
      tab: 'HBL',
    },
    {
      key: 'MBL',
      tab: 'MBL',
    },
    {
      key: 'INV',
      tab: 'INVOICE',
    },
  ];

  componentDidMount() {
    const { mbl } = this.props;
    this.setCurrent(mbl);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.mbl !== this.props.mbl) {
      console.log("RECEIVE MBL:", nextProps.mbl);
      this.setCurrent(nextProps.mbl);
    }
  }

  setCurrent(mbl) {
    this.setState({ current: mbl });
  }

  handleTabChange = key => {
    const { match } = this.props;
    switch (key) {
      case 'MBL':
        router.push(`${match.url}/MBL`);
        break;
      case 'HBL':
        router.push(`${match.url}/HBL`);
        break;
      case 'INV':
        router.push(`${match.url}/INV`);
        break;
      default:
        break;
    }
  };

  handleLockClick() {
    const { current } = this.state;
    if (current.isLock === 0) {
      this.setState({
        lockFormVisible: true,
      });
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: `${ModelName}/lockBill`,
        payload: {
          id: current.id,
          isLock: 1 - current.isLock,
        },
      });
    }
  }

  handleLockFormSubmit() {
    const { dispatch } = this.props;
    const { form } = this.lockForm.props;
    const { current } = this.state;

    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const payload = {
        id: current.id,
        isLock: 1 - current.isLock,
        lockDate: Utils.getChineseDate(values.lockDate),
      };

      dispatch({
        type: `${ModelName}/lockBill`,
        payload: payload,
        callback: resp => {
          if (resp) {
            this.setState({ lockFormVisible: false });
          }
        },
      });
    });
  }

  handleSubmit() {
    const { dispatch } = this.props;
    const { form } = this.mblEditForm.props;
    const { current } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      dispatch({
        type: `${ModelName}/updateHeaderInfo`,
        payload: {
          id: current.id,
          ...fieldsValue,
          year: fieldsValue.yearMonth ? fieldsValue.yearMonth.year() : 0,
          month: fieldsValue.yearMonth ? fieldsValue.yearMonth.month() + 1 : 0,
        },
        callback: resp => {
          if (resp) {
            this.setState({ visible: false });
          }
        },
      });
    });
  }

  render() {
    const { match, children, location, cUser } = this.props;

    const { lockFormVisible, visible, current } = this.state;

    const Authorized = RenderAuthorized(cUser.sys_Role.enCode);

    const action = () => (
      <div style={{ flex: 'inline' }}>
        <Authorized authority={['SysAdmin', 'SysOperator']} >
          <Button type="default" onClick={() => this.setState({ visible: true })}>编辑船运信息</Button>
          <Button type="default" onClick={() => this.handleLockClick()}>
            {current && current.isLock === 1 ? '解锁' : '主单核销'}
          </Button>
        </Authorized>
      </div>
    );

    const titleContent = () => (
      current &&
      <div style={{ display: 'flex' }}>
        <span style={{ color: current && current.isLock === 1 ? 'green' : 'red' }}>{current.lockDate ? '核销日期：' + Utils.getChineseDate(current.lockDate) : '[未核销]'}</span>
        <Tooltip title={current && current.id}>
          <span style={{ marginLeft: '1em' }}>{current.objectNumber}</span>/
          <span>{current.so}</span>
        </Tooltip>
        <span style={{ marginLeft: '1em' }}>{current.salerName}</span>
        <span>({current.year + '-' + current.month})</span>
      </div>
    );

    return (
      <div>
        <PageHeaderWrapper
          className={styles.pageHeader}
          title={titleContent()}
          action={action()}
          tabList={this.tabList}
          tabActiveKey={location.pathname.replace(`${match.url}/`, '')}
          onTabChange={this.handleTabChange}
        >
          {children}
        </PageHeaderWrapper>
        <MBLEditForm
          visible={visible}
          bill={current}
          onOk={() => this.handleSubmit()}
          onCancel={() => this.setState({ visible: false })}
          getInstance={form => (this.mblEditForm = form)}
        />
        <LockBillForm
          visible={lockFormVisible}
          onOk={() => this.handleLockFormSubmit()}
          onCancel={() => this.setState({ lockFormVisible: false })}
          getInstance={form => (this.lockForm = form)}
        />
      </div>
    );
  }
}

export default Framework;
